<template>
    <div class="process-page">
        <van-nav-bar title="流程图" left-text="返回" left-arrow  @click-left="onClickLeft" @click-right="onClickRight">
        </van-nav-bar>
        <div id="container" ref="container" style="width: 100%;height: 100%;pointer-events: auto;  /* 允许事件穿透 */"></div>
        <van-popup v-model:show="nodeDetails" style="width: 80%;border-radius: 20px;">
            <div style="padding: 20px 0;">
                <van-cell-group >
                    <van-cell title="姓名" :value="target.userName" icon="location-o" is-link  />
                    <van-cell title="部门" :value="target.deptName" icon="location-o" is-link  />
                </van-cell-group>
                <h3>相关流程</h3>
                 <div>
                    <div style="display: flex;">
                        <span style="flex: 1;">发送人</span>
                        <span style="flex: 1;">是否签收</span>
                        <span style="flex: 1;">是否销毁</span>
                        <span style="width: 30%;">签名</span>
                    </div>
                    <div style="display: flex;" v-for="(item,index) in target.detailInfos" :key="index">
                        <span style="flex: 1;">{{ item.senderName }}</span>
                        <span style="flex: 1;">{{ item.status==1?'否':'是' }}</span>
                        <span style="flex: 1;">{{ item.isDestroyed==1?'否':'是' }}</span>
                        <span style="width: 30%;">
                            <img  @click="showImg(item.filePath.replace('http://10.131.231.114:8080', 'https://sn.wgt.10086.cn'))" v-if="item.filePath" style="width: 100%;"  :src="item.filePath.replace('http://10.131.231.114:8080', 'https://sn.wgt.10086.cn')"/>
                            <span v-else>暂无</span>
                        </span>
                    </div>
                 </div>
            </div>

        </van-popup>
    </div>
</template>

<script setup>
import { useRouter, useRoute } from "vue-router";
import { onMounted, ref, nextTick } from "vue";
import { Graph } from '@antv/x6';
import { register } from '@antv/x6-vue-shape'
// import { Export } from '@antv/x6-plugin-export'
import DistributionInfoApi from '../api/distribution'
import itemDiv from "./item.vue"
import { Toast,ImagePreview } from "vant";
import dagre from 'dagre'
console.log(Graph)
let graphTarget = null
let target = ref({})
let nodeDetails = ref(false)
let startPoint = null;
const router=useRouter()
const route = useRoute();
let container = ref()
const onClickLeft = () => router.push('/distribution');
const onClickRight = () => router.push('/recordsInfo/add');
onMounted(() => {
    register({
        shape: 'custom-vue-node',
        width: 180,
        height: 70,
        component:itemDiv

    })
    nextTick(() => {
        graphTarget = new Graph({
            container: container.value,
            panning: {
                enabled: true,
                eventTypes: ['leftMouseDown', 'touch'], // 同时支持鼠标和触摸
                // 可选：指定触发平移的手指数目
                fingerNumber: 1, // 单指平移
                // 可选：排除某些元素不触发平移
                exclude: ['rect', 'circle'], // 不阻止节点上的平移
            },
            // 鼠标滚轮/触摸板配置
            mousewheel: {
                enabled: true,
                modifiers: [], // 移动端不需要修饰键
            },

            // 防止默认行为
            preventDefaultContextMenu: true,
            preventDefaultBlankAction: true,
            interacting: false,
            background: {
                color: '#F2F7FA',
            },
        })
        console.log(graphTarget,1111111111)
        const nodes = [
        ]
        const edges = [
        ]
        // this.content = this.$route.query.content

        DistributionInfoApi.getDistributionTree({ 'distributionId': route.query.distributionId, 'relationId': route.query.relationId }).then(res => {
            console.log(graphTarget,22222222222)
            let respData = res.data.data.data
            respData.nodes.forEach(item => {
                nodes.push(cNodeDom(item))
            })
            respData.relations.forEach(item => {
                edges.push(cEdge(nodes[item.source], nodes[item.target]))
            })
            graphTarget.resetCells([...nodes, ...edges])
            layout()
            graphTarget.zoomTo(0.8)
            graphTarget.centerContent()
            graphTarget.on('node:click', ({ node, view }) => {
           
                // let Sstatus = store.getters.userid == node.data.receiverId
                // if (node.data.roleName == '数据支撑') return Toast.fail("根节点无法获取信息")
                DistributionInfoApi.getDistributionDetail({ nodeId: node.data.nodeId, senderId:  node.data.senderId  }).then(res => {
                    if (res.data.code == 200) {
                        target.value = res.data.data
                        nodeDetails.value = true
                    }
                })
            });
            // graphTarget.use(new Export())
            const touchArea = document.getElementById("container");

            // 开始触摸了
            touchArea.addEventListener("touchstart", (e) => {
            
                // 这行是为了解决拖动画布后，节点又没法拖了……
                if (e.target.className.baseVal !== "x6-graph-svg") return false;
                startPoint = { x: e.touches[0].clientX, y: e.touches[0].clientY };
                // graphTarget.translateBy(startPoint)
            });
            // 开始触摸移动
            touchArea.addEventListener("touchmove", (e) => {
                if (startPoint) {
                    const dx = e.touches[0].clientX - startPoint.x;
                    const dy = e.touches[0].clientY - startPoint.y;
                    graphTarget.translateBy(dx, dy);
                    startPoint = { x: e.touches[0].clientX, y: e.touches[0].clientY };
                    //  graphTarget.translateBy(startPoint)
                }
            });
            // 触摸结束记得重置坐标
            touchArea.addEventListener("touchend", (e) => {
                startPoint = null;
                //graphTarget.translateBy(startPoint)
            });
        })

    })
})
function cNodeDom(params) {
    console.log(graphTarget,3333)
    return  graphTarget.createNode({
        id: params.id,
        shape: 'custom-vue-node',
        data: params,


    })
}
function cEdge(source, target) {
    console.log(graphTarget,22222222222)
    return  graphTarget.createEdge({
        source: { cell: source.id },
        target: { cell: target.id },
        attrs: {
            line: {
                strokeWidth: 2,
                stroke: '#1890FF',
                targetMarker: 'classic',
            },

        },
        router: {
            name: 'metro',
            args: {
                startDirections: ['bottom'],
                endDirections: ['top'],
            },
        },
    })
}

function layout() {
    const dir = 'TB'
    const nodes = graphTarget.getNodes()
    const edges = graphTarget.getEdges()
    const g = new dagre.graphlib.Graph()
    g.setGraph({ rankdir: dir, nodesep: 180, ranksep: 70, preventOverlap: true, })
    g.setDefaultEdgeLabel(() => ({}))
    const width = 180
    const height = 70
    nodes.forEach((node) => {
        g.setNode(node.id, { width, height })
    })
    edges.forEach((edge) => {
        const source = edge.getSource()
        const target = edge.getTarget()
        g.setEdge(source.cell, target.cell)
    })
    dagre.layout(g)
    g.nodes().forEach((id) => {
        const node = graphTarget.getCellById(id)
        if (node) {
            const pos = g.node(id)
            node.position(pos.x, pos.y)
        }
    })
    // edges.forEach((edge) => {
    //   const source = edge.getSourceNode()
    //   const target = edge.getTargetNode()
    //   const sourceBBox = source.getBBox()
    //   const targetBBox = target.getBBox()

    //   if ((dir === 'LR' || dir === 'RL') && sourceBBox.y !== targetBBox.y) {
    //     const gap =
    //       dir === 'LR'
    //         ? targetBBox.x - sourceBBox.x - sourceBBox.width
    //         : -sourceBBox.x + targetBBox.x + targetBBox.width
    //     const fix = dir === 'LR' ? sourceBBox.width : 0
    //     const x = sourceBBox.x + fix + gap / 2
    //     edge.setVertices([
    //       { x, y: sourceBBox.center.y },
    //       { x, y: targetBBox.center.y },
    //     ])


    //   } else if (
    //     (dir === 'TB' || dir === 'BT') &&
    //     sourceBBox.x !== targetBBox.x
    //   ) {
    //     const gap =
    //       dir === 'TB'
    //         ? targetBBox.y - sourceBBox.y - sourceBBox.height
    //         : -sourceBBox.y + targetBBox.y + targetBBox.height
    //     const fix = dir === 'TB' ? sourceBBox.height : 0
    //     const y = sourceBBox.y + fix + gap / 2
    //     edge.setVertices([
    //       { x: sourceBBox.center.x, y },
    //       { x: targetBBox.center.x, y },
    //     ])
    //   } else {
    //     edge.setVertices([])
    //   }
    // })
}
const showImg = (url) => {
  ImagePreview([
    url
  ]);
}
</script>
<style scoped>
.process-page {
    background: #ebedf0;
    width: 100%;
    height: 100vh;
    pointer-events: auto;
    /* display: flex;
    flex-direction: column;
    pointer-events: auto; */
    /* 允许事件穿透 */
}
:deep(.van-cell__title) {
    text-align: left;
}
</style>